package com.jinrustar.httpfileserver.core.ws;

import com.jinrustar.httpfileserver.core.http.HttpFileServer;
import com.jinrustar.httpfileserver.springboot.Application;
import com.jinrustar.httpfileserver.util.CommonUtil;
import com.jinrustar.httpfileserver.util.WebUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.UnknownHostException;

import static com.jinrustar.httpfileserver.core.http.HttpFileServer.ipAndPort;
import static com.jinrustar.httpfileserver.springboot.Application.getLocalIpWithBlock;

public class WebSocketServer {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);


    public void run(int port, Application.StartSuccessCallback startSuccessCallback) throws UnknownHostException, InterruptedException {


        String localIp = getLocalIpWithBlock();

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workGroup);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(new ChildChannelHandler());

            logger.debug("WebSocket服务端开启等待客户端连接... port:{}", port);

    /*        HttpFileServer.wsClient = new WSClient(); *//*连接客户端用于发送消息到前端页面*//*

*/
            if (startSuccessCallback != null) {
                startSuccessCallback.onSuccess(HttpFileServer.IP, "webSocketServer");
            }
            Channel ch = b.bind(port).sync().channel();


            ch.closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
